package com.xaaef.authorize.server.controller;

import com.xaaef.authorize.common.exception.OAuth2Exception;
import com.xaaef.authorize.common.util.JsonResult;
import com.xaaef.authorize.server.params.LoginParam;
import com.xaaef.authorize.server.params.TencentModeParam;
import com.xaaef.authorize.server.service.TencentAuthorizeService;
import com.xaaef.authorize.server.token.OAuth2Token;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * All rights Reserved, Designed By www.xaaef.com
 * <p>
 * 腾讯QQ和微信授权模式
 * </p>
 *
 * @author Wang Chen Chen
 * @version 1.0.1
 * @date 2021/7/15 16:59
 * @copyright 2021 http://www.xaaef.com Inc. All rights reserved.
 */

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("tencent")
public class TencentController {

    private TencentAuthorizeService tencentAuthorizeService;

    /**
     * 获取 QQ 授权回调页面
     *
     * @author Wang Chen Chen
     * @date 2021/8/5 15:26
     */
    @PostMapping("qq")
    public JsonResult<String> qq(@RequestBody @Validated TencentModeParam param, BindingResult br) {
        if (br.hasErrors()) {
            return JsonResult.fail(br.getFieldError().getDefaultMessage());
        }
        try {
            String address = tencentAuthorizeService.buildQQAuthAddress(param);
            return JsonResult.success(null, address);
        } catch (OAuth2Exception e) {
            return JsonResult.error(e.getStatus(), e.getMessage());
        }
    }


    /**
     * 获取 QQ 授权回调 地址
     *
     * @author Wang Chen Chen
     * @date 2021/8/5 15:26
     */
    @RequestMapping("qq/callback")
    public JsonResult<String> qqCallback(String code, String state) {
        try {
            OAuth2Token oAuth2Token = tencentAuthorizeService.QqAuthorize(code, state);
            return JsonResult.success(null, oAuth2Token);
        } catch (OAuth2Exception e) {
            return JsonResult.error(e.getStatus(), e.getMessage());
        }
    }


    @PostMapping("wechat")
    public JsonResult<String> weChat(@RequestBody @Validated TencentModeParam param, BindingResult br) {
        if (br.hasErrors()) {
            return JsonResult.fail(br.getFieldError().getDefaultMessage());
        }
        return JsonResult.success(null, "");
    }


}
